﻿// -----------------------------------------------------------------------
// <copyright file="ConfigurationViewModel.cs" company="Matthieu Klotz">
// Copyright (c) 2012, Matthieu Klotz
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of Matthieu Klotz nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <summary>ViewModel for configuration user control.</summary>
// -----------------------------------------------------------------------

namespace AppFabric.Admin.Client.Core.ViewModel
{
    using System.Collections.ObjectModel;
    using System.Threading;
    using System.Windows.Input;
    using AppFabric.Admin.Client.Core.Services;
    using GalaSoft.MvvmLight.Command;
    using Microsoft.Practices.ServiceLocation;

    /// <summary>ViewModel for configuration user control.</summary>
    public class ConfigurationViewModel : ItemCollectionViewModel<Model.Environment>
    {
        /// <summary>
        /// Command executed when the control is loaded.
        /// </summary>
        private AsyncRelayCommand controlLoadedCommand;

        /// <summary>
        /// Command executed for adding a new environment.
        /// </summary>
        private RelayCommand addEnvironmentCommand;

        /// <summary>
        /// Command executed for removing an environment.
        /// </summary>
        private RelayCommand removeEnvironmentCommand;

        /// <summary>
        /// Command executed for editing an environment.
        /// </summary>
        private RelayCommand editEnvironmentCommand;

        /// <summary>
        /// Command executed for adding a new cache cluster.
        /// </summary>
        private RelayCommand addClusterCommand;

        /// <summary>
        /// Command executed for removing a cache cluster.
        /// </summary>
        private RelayCommand removeClusterCommand;

        /// <summary>
        /// Command executed for saving an environment.
        /// </summary>
        private AsyncRelayCommand saveEnvironmentCommand;

        /// <summary>
        /// Indicates whether the selecting environment can be edited or not.
        /// </summary>
        private bool canEditSelectedValue;

        /// <summary>
        /// Gets or sets a value indicating whether this instance can edit the selected environment.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance can edit the selected environment; otherwise, <c>false</c>.
        /// </value>
        public bool CanEditSelectedValue
        {
            get
            {
                return this.canEditSelectedValue;
            }

            set
            {
                this.canEditSelectedValue = value;
                this.RaisePropertyChanged("CanEditSelectedValue");
            }
        }

        /// <summary>
        /// Gets the save environment command.
        /// </summary>
        /// <value>The command for saving an environment.</value>
        public ICommand SaveEnvironmentCommand
        {
            get
            {
                if (this.saveEnvironmentCommand == null)
                {
                    this.saveEnvironmentCommand = new AsyncRelayCommand(this.SaveEnvironment);
                }

                return this.saveEnvironmentCommand;
            }
        }

        /// <summary>
        /// Gets the control loaded command.
        /// </summary>
        /// <value>The command executed when the control is loaded.</value>
        public ICommand ControlLoadedCommand
        {
            get
            {
                if (this.controlLoadedCommand == null)
                {
                    this.controlLoadedCommand = new AsyncRelayCommand(this.LoadEnvironments);
                }

                return this.controlLoadedCommand;
            }
        }

        /// <summary>
        /// Gets the add environment command.
        /// </summary>
        /// <value>The command for adding a new environment.</value>
        public ICommand AddEnvironmentCommand
        {
            get
            {
                if (this.addEnvironmentCommand == null)
                {
                    this.addEnvironmentCommand = new RelayCommand(this.AddEnvironment);
                }

                return this.addEnvironmentCommand;
            }
        }

        /// <summary>
        /// Gets the remove environment command.
        /// </summary>
        /// <value>The command for removing an environment.</value>
        public ICommand RemoveEnvironmentCommand
        {
            get
            {
                if (this.removeEnvironmentCommand == null)
                {
                    this.removeEnvironmentCommand = new RelayCommand(this.RemoveEnvironment);
                }

                return this.removeEnvironmentCommand;
            }
        }

        /// <summary>
        /// Gets the edit environment command.
        /// </summary>
        /// <value>The command for editing an environment.</value>
        public ICommand EditEnvironmentCommand
        {
            get
            {
                if (this.editEnvironmentCommand == null)
                {
                    this.editEnvironmentCommand = new RelayCommand(this.EditEnvironment);
                }

                return this.editEnvironmentCommand;
            }
        }

        /// <summary>
        /// Gets the add cluster command.
        /// </summary>
        /// <value>The command for adding a new cache cluster.</value>
        public ICommand AddClusterCommand
        {
            get
            {
                if (this.addClusterCommand == null)
                {
                    this.addClusterCommand = new RelayCommand(this.AddCluster);
                }

                return this.addClusterCommand;
            }
        }

        /// <summary>
        /// Gets the remove cluster command.
        /// </summary>
        /// <value>The command for removing a cache cluster.</value>
        public ICommand RemoveClusterCommand
        {
            get
            {
                if (this.removeClusterCommand == null)
                {
                    this.removeClusterCommand = new RelayCommand(this.RemoveCluster);
                }

                return this.removeClusterCommand;
            }
        }

        /// <summary>
        /// Gets the client configuration service.
        /// </summary>
        private static IClientConfigurationService ClientConfigurationService
        {
            get
            {
                return ServiceLocator.Current.GetInstance<IClientConfigurationService>();
            }
        }

        /// <summary>
        /// Removes the environment from the configuration.
        /// </summary>
        /// <param name="environment">The environment to remove.</param>
        private static void RemoveEnvironmentFromConfiguration(object environment)
        {
            Model.Environment environmentToRemove = environment as Model.Environment;
            if (environmentToRemove != null && !string.IsNullOrWhiteSpace(environmentToRemove.Name))
            {
                ClientConfigurationService.RemoveEnvironment(environmentToRemove);
            }
        }

        /// <summary>
        /// Loads the environments.
        /// </summary>
        private void LoadEnvironments()
        {
            if (this.Items == null)
            {
                ObservableCollection<Model.Environment> environments = ClientConfigurationService.GetEnvironments();
                if (environments == null)
                {
                    environments = new ObservableCollection<Model.Environment>();
                }

                this.Items = environments;
            }
        }

        /// <summary>
        /// Adds a new environment.
        /// </summary>
        private void AddEnvironment()
        {
            Model.Environment environment = new Model.Environment();
            environment.Childs = new ObservableCollection<Model.Node>();
            this.Items.Add(environment);
            this.SelectedIndex = this.Items.Count - 1;
            this.EditEnvironment();
        }

        /// <summary>
        /// Removes the current selected environment.
        /// </summary>
        private void RemoveEnvironment()
        {
            Model.Environment environment = this.SelectedValue;
            if (environment != null)
            {
                ThreadPool.QueueUserWorkItem(RemoveEnvironmentFromConfiguration, environment);
                this.Items.Remove(environment);
            }
        }

        /// <summary>
        /// Allows edit mode on the current environment.
        /// </summary>
        private void EditEnvironment()
        {
            this.CanEditSelectedValue = true;
        }

        /// <summary>
        /// Adds a new cache cluster to the current environment.
        /// </summary>
        private void AddCluster()
        {
            if (this.SelectedValue != null)
            {
                Model.Cluster cluster = new Model.Cluster();
                cluster.Parent = this.SelectedValue;
                this.SelectedValue.Childs.Add(cluster);
            }
        }

        /// <summary>
        /// Removes the cluster to the current environemnt.
        /// </summary>
        private void RemoveCluster()
        {
            if (this.SelectedChildIndex >= 0)
            {
                this.SelectedValue.Childs.RemoveAt(this.SelectedChildIndex);
            }
        }

        /// <summary>
        /// Saves the current environment.
        /// </summary>
        private void SaveEnvironment()
        {
            Model.Environment environment = this.SelectedValue;
            if (environment != null && !string.IsNullOrWhiteSpace(environment.Name))
            {
                ClientConfigurationService.AddOrUpdateEnvironment(environment);
            }
        }
    }
}